import React, { useRef, useState } from 'react';
import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
import {
  Button,
  Tag,
  Space,
  Menu,
  Dropdown,
  message,
  Form,
  Modal,
  Input,
  Select,
  Popconfirm,
  Breadcrumb,
} from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import { useRequest, Link, history } from 'umi';

import request from 'umi-request';
const { Option } = Select;

export default () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [Copyform] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  //新建模板
  const addModule = useRequest(
    (data) => {
      return {
        url: `http://10.1.40.84:9993/addModule`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  //根据boardId获取单个画板数据
  const getOneModuleData = useRequest(
    (moduleId) => {
      return {
        url: `http://10.1.40.84:9993/getOneModuleData?moduleId=${moduleId}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  //获取所有用途
  const getAllPurpose = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9993/getAllPurpose`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        // window.open(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  const showModal = (record: any) => {
    console.log(record);
    getOneModuleData.run(record.id).then((e) => {
      setIsModalVisible(true);
      console.log(JSON.parse(e));
    });
  };
  const handleOk = () => {
    Copyform.validateFields().then((formdata) => {
      // console.log(formdata);
      // console.log(JSON.parse(getOneModuleData.data));
      addModule
        .run({
          moduleName: formdata.moduleName,
          desc: formdata.desc,
          boardList: JSON.parse(getOneModuleData.data).data,
          purposeId: formdata.purposeId,
        })
        .then(() => {
          getAllModule.run();
        });
    });
    setIsModalVisible(false);
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  //获取全部模版的请求
  const getAllModule = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getAllModule',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      // onSuccess: (result, params) => {
      //     console.log(JSON.parse(result));
      // },
      // onError: (e, params) => {
      //     console.log(e);
      //     console.log(params);
      // },
      manual: true,
    },
  );
  //删除模版
  const deleteModule = useRequest(
    (moduleId) => {
      return {
        url: `http://10.1.40.84:9993/deleteModule?moduleId=${moduleId}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      onSuccess: (result, params) => {
        message.success(result?.msg || '操作成功！！！');
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
      formatResult: (res) => res,
    },
  );

  const columns = [
    // {
    //     dataIndex: 'index',
    //     valueType: 'indexBorder',
    //     width: 48,
    // },
    {
      title: '模版名称',
      dataIndex: 'name',
      copyable: true,
      ellipsis: true,
      // tip: '标题过长会自动收缩',
      // formItemProps: {
      //     rules: [
      //         {
      //             required: true,
      //             message: '此项为必填项',
      //         },
      //     ],
      // },
    },
    {
      title: '模版描述',
      dataIndex: 'descr',
      key: 'descr',
      hideInSearch: true,
      // align: 'center',
    },

    {
      title: '创建人',
      dataIndex: 'createUser',
      key: 'createUser',
    },
    {
      title: '模版用途',
      key: 'purposeName',
      dataIndex: 'purposeName',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      align: 'center',
      hideInSearch: true,
      sorter: {
        compare: (a: { createTime: string }, b: { createTime: string }) =>
          b.createTime.localeCompare(a.createTime),
      },
    },
    {
      title: '最后修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      align: 'center',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <Link
          to={'/IntelligentReport/CreateIntelligentReport/' + record.id}
          key="view"
        >
          查看
        </Link>,
        // <a
        //   key="复制"
        //   onClick={() => {
        //     showModal(record);
        //   }}
        // >
        //   复制
        // </a>,
        <Popconfirm
          key={'2'}
          title="确定删除吗？"
          onConfirm={() => {
            deleteModule.run(record.id).then(() => {
              getAllModule.run();
            });
          }}
          onCancel={() => {
            message.error('已取消');
          }}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: ' ',
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>数据导出</Breadcrumb.Item>
            <Breadcrumb.Item>智能报表</Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
    >
      <ProTable
        columns={columns}
        actionRef={actionRef}
        cardBordered
        loading={getOneModuleData.loading}
        dataSource={getAllModule?.data || []}
        request={async (param) => {
          var temp: any;
          await getAllModule.run(param).then((data) => {
            temp = data;
          });
          return {
            data: temp,
            success: true,
          };
        }}
        rowKey="id"
        // search={false}
        search={{
          labelWidth: 'auto',
          defaultCollapsed: true,
          optionRender: (searchConfig, formProps, dom) => [
            ...dom.reverse(),
            // <Button
            //     key="out"
            //     onClick={() => {
            //         const values = searchConfig?.form?.getFieldsValue();
            //         console.log(values);
            //     }}
            // >
            //     导出
            // </Button>,
          ],
        }}
        onSubmit={(e) => {
          getAllModule.run({
            name: e.name,
            account: e.createUser,
          });
        }}
        formRef={form}
        onReset={() => {
          getAllModule.run();
          form.resetFields();
        }}
        options={{
          reload: false,
        }}
        dateFormatter="string"
        headerTitle="模版列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() =>
              history.push('/IntelligentReport/CreateIntelligentReport/new')
            }
          >
            新建模版
          </Button>,
        ]}
      />
      <Modal
        title="复制模版"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form layout="horizontal" form={Copyform}>
          <Form.Item
            label="模版名称"
            name="moduleName"
            rules={[{ required: true }]}
          >
            <Input allowClear />
          </Form.Item>
          <Form.Item label="模版描述" name="desc" rules={[{ required: true }]}>
            <Input allowClear />
          </Form.Item>
          <Form.Item
            label="模版用途"
            name="purposeId"
            rules={[{ required: true }]}
          >
            {/* <Select >
                            {
                                (getAllPurpose.data || []).map((item: any) => {
                                    return (
                                        <Option value={item.id} key={item.id} >{item.purposeName}</Option>
                                    )
                                })
                            }
                        </Select> */}
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};
